package com.everflourish.yeah100.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.everflourish.yeah100.R;
import com.everflourish.yeah100.utils.CommonUtil;
import com.everflourish.yeah100.utils.ResourcesUtil;
import com.everflourish.yeah100.utils.SPUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 修改单个答案对话框
 *
 * @author pf
 * @date 2015-4-23
 */
public class SingleAnswerDialog extends Dialog implements DialogInterface {

    private static final String IS_CHECKED = "isChecked";
    private static final String ITEM = "item";
    public static final int BUTTON_CONFIRM = -1;

    public static final int BUTTON_CANCEL = -2;

    private Context mContext;
    private TextView mTitleTv, mMsgTv;
    private ListView mSingleLv;
    private String mTitle, mMsg;
    // private List<String> mItems;
    private List<Map<String, Object>> mItems;
    private List<Map<String, Object>> mTempItems;
    private LinearLayout mSureInputLl;
    public Button mCancelBtn, mConfirmBtn, mSureBtn;
    private String mCancelName, mConfirmName, mSureName;

    private OnClickListener onClickListener;
    private OnClickListener onCancelListener, onConfirmListener,
            onSureListener;
    private boolean isSingle = true;
    private boolean isInputEtShow;
    private TextView mShrinkTv;
    private EditText mSureEt;

    public SingleAnswerDialog(Context context, String title, String msg,
                              boolean isSingle, boolean isInputEtShow) {
        super(context, R.style.MyDialog);
        this.mContext = context;
        setContentView(R.layout.dialog_single_answer);

        mShrinkTv = (TextView) this.findViewById(R.id.shrink);
        mTitleTv = (TextView) this.findViewById(R.id.title_tv);
        mMsgTv = (TextView) this.findViewById(R.id.msg_tv);
        mSingleLv = (ListView) this.findViewById(R.id.single_lv);
        mConfirmBtn = (Button) this.findViewById(R.id.cancel_btn);
        mCancelBtn = (Button) this.findViewById(R.id.confirm_btn);
        mSureInputLl = (LinearLayout) this.findViewById(R.id.scorce_put);
        mSureBtn = (Button) this.findViewById(R.id.sure);
        mSureEt = (EditText) this.findViewById(R.id.scorceEt);
        this.isInputEtShow = isInputEtShow;
        this.mTitle = title;
        this.mMsg = msg;
        this.isSingle = isSingle;
    }

    public SingleAnswerDialog(Context context) {
        this(context, null, null, true, false);
    }

    /**
     * 设置标题
     *
     * @param title
     * @return
     */
    public SingleAnswerDialog setTitle(String title) {
        this.mTitle = title;
        return this;
    }

    /**
     * 设置消息内容
     *
     * @param msg
     * @return
     */
    public SingleAnswerDialog setMsg(String msg) {
        this.mMsg = msg;
        return this;
    }

    public String getInputStr() {
        return mSureEt.getText().toString();
    }

    public SingleAnswerDialog setItems(List<String> items, String answer,
                                       OnClickListener listener) {
        char[] content = answer.toCharArray();
        // this.mItems = items;
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (String s : items) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put(IS_CHECKED, false);
            map.put(ITEM, s);
            for (int i = 0; i < content.length; i++) {
                String oldAnswer = content[i] + "";
                if (s.equals(oldAnswer)) {
                    map.put(IS_CHECKED, true);
                    break;
                }
            }
            list.add(map);
        }
        mItems = list;
        mTempItems = CommonUtil.deepCopy(mItems);
        this.onClickListener = listener;
        return this;
    }

    /**
     * 设置确定按钮
     *
     * @param btnName         按钮名称
     * @param onClickListener 按钮监听
     * @return PromptDialog
     */
    public SingleAnswerDialog setOnConfirmButton(String btnName,
                                                 OnClickListener onClickListener) {
        this.mConfirmName = btnName;
        this.onConfirmListener = onClickListener;
        return this;
    }

    /**
     * 设置取消按钮
     *
     * @param btnName         按钮名称
     * @param onClickListener 按钮监听
     * @return PromptDialog
     */
    public SingleAnswerDialog setOnCancelButton(String btnName,
                                                OnClickListener onClickListener) {
        this.mCancelName = btnName;
        this.onCancelListener = onClickListener;
        return this;
    }

    public SingleAnswerDialog setOnSureButton(String btnName,
                                              OnClickListener onClickListener) {
        this.mSureName = btnName;
        this.onSureListener = onClickListener;
        return this;
    }

    @Override
    public void show() {
        createDialog();
        super.show();
    }

    private SingleAnswerDialog createDialog() {
        shrink(false);
        if (mTitle == null) {
            mTitleTv.setVisibility(View.GONE);
        } else {
            mTitleTv.setText(mTitle);
        }
        if (mMsg == null) {
            mMsgTv.setVisibility(View.GONE);
        } else {
            mMsgTv.setText(mMsg);
        }
        if (isInputEtShow) {
            mSureInputLl.setVisibility(View.VISIBLE);
        }
        if (mItems == null) {
            mSingleLv.setVisibility(View.GONE);
        } else {
            mSingleLv.setAdapter(singleAdapter);
        }
        if (onClickListener != null) {
            mSingleLv
                    .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent,
                                                View view, int position, long id) {
                            if (isSingle) {

                                for (Map<String, Object> m : mItems) {
                                    m.put(IS_CHECKED, false);
                                }
                                mItems.get(position).put(IS_CHECKED, true);
                                onClickListener.onClick(
                                        SingleAnswerDialog.this, position);
                                SingleAnswerDialog.this.dismiss();
                            } else {// 多选
                                if (mItems.get(position).get(ITEM).equals("未填")) {
                                    mItems.get(position).put(IS_CHECKED, true);
                                    onClickListener.onClick(
                                            SingleAnswerDialog.this, position);
                                    SingleAnswerDialog.this.dismiss();
                                } else {
                                    boolean isChecked = (Boolean) mItems.get(
                                            position).get(IS_CHECKED);
                                    mItems.get(position).put(IS_CHECKED,
                                            !isChecked);
                                    ((BaseAdapter) mSingleLv.getAdapter())
                                            .notifyDataSetChanged();
                                }
                            }
                        }
                    });
        }

        if (onConfirmListener != null) {
            mConfirmBtn.setText(mConfirmName);
            mConfirmBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItems.clear();
                    mItems.addAll(mTempItems);
                    onConfirmListener.onClick(SingleAnswerDialog.this,
                            BUTTON_CONFIRM);
                }
            });
        } else {
            mConfirmBtn.setVisibility(View.GONE);
        }

        if (onSureListener != null) {
            mSureBtn.setText(mSureName);
            mSureBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onSureListener.onClick(SingleAnswerDialog.this,
                            BUTTON_CONFIRM);
                }
            });
        } else {
            mSureBtn.setVisibility(View.GONE);
        }

        if (onCancelListener != null) {
            mCancelBtn.setText(mCancelName);
            mCancelBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItems.clear();
                    mItems.addAll(mTempItems);
                    onCancelListener.onClick(SingleAnswerDialog.this,
                            BUTTON_CANCEL);
                }
            });
        } else {
            mCancelBtn.setVisibility(View.GONE);
        }

        mShrinkTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shrink(true);
            }
        });
        return this;
    }

    private Boolean isCancelShrinkFlag = false;

    public void setIsCancelShrinkFlag(boolean isCancelShrinkFlag) {
        this.isCancelShrinkFlag = isCancelShrinkFlag;
        if (isCancelShrinkFlag) {
            mShrinkTv.setVisibility(View.GONE);
        } else {
            mShrinkTv.setVisibility(View.VISIBLE);
        }
    }

    private void shrink(boolean isSave) {
        SPUtil spUtil = SPUtil.getSharedPreferences(mContext);
        boolean isShrink = spUtil.getBoolean(SPUtil.IS_SHRINK, true);
        if (!isSave) {
            isShrink = !isShrink;
        } else {
            spUtil.putBoolean(SPUtil.IS_SHRINK, !isShrink);
        }
        mItems.clear();
        if (isShrink || isCancelShrinkFlag) {
            // 如果是，将展开
            mItems.addAll(mTempItems);
            singleAdapter.notifyDataSetChanged();
            mShrinkTv.setText("∧");
        } else {
            for (int i = 0; i < 4; i++) {
                mItems.add(mTempItems.get(i));
            }
            mShrinkTv.setText("∨");
            singleAdapter.notifyDataSetChanged();
        }
    }

    public ListView getListView() {
        return mSingleLv;
    }

    public String getAnswer() {
        String answer = "";
        for (Map<String, Object> m : mItems) {
            if ((Boolean) m.get(IS_CHECKED)) {
                String item = (String) m.get(ITEM);
                answer += item;
            }
        }
        return answer;
    }

    BaseAdapter singleAdapter = new BaseAdapter() {

        @Override
        public int getCount() {
            return mItems.size();
        }

        @Override
        public Object getItem(int position) {
            return mItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        //        @TargetApi(Build.VERSION_CODES.M)
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            String item = (String) mItems.get(position).get(ITEM);
            boolean isChecked = (Boolean) mItems.get(position).get(IS_CHECKED);
            TextView tv = new TextView(mContext);
//            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
//                tv.setBackground(ResourcesUtil.getDrawable(mContext, R.drawable.rect_list_ripple));
//            }
            tv.setWidth(LayoutParams.MATCH_PARENT);
            tv.setHeight((int) ResourcesUtil.getDimension(mContext,
                    R.dimen.dialog_single_item_height));
            tv.setPadding(10, 0, 10, 0);
            tv.setTextSize(15);
            tv.setGravity(Gravity.CENTER_VERTICAL);
            tv.setTextColor(Color.BLACK);
            tv.setText(item);
            if (isSingle) {
                if (isChecked) {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                        tv.setBackground(ResourcesUtil.getDrawable(mContext, R.drawable.rect_list_ripple_selected));
                    } else {
                        tv.setBackgroundColor(ResourcesUtil.getColor(mContext,
                                R.color.message_item_selected));
                    }
                } else {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                        tv.setBackground(ResourcesUtil.getDrawable(mContext, R.drawable.rect_list_ripple));
                    } else {
                        tv.setBackgroundColor(ResourcesUtil.getColor(mContext,
                                R.color.message_item_double));
                    }
                }
            } else {
                if (isChecked) {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                        tv.setBackground(ResourcesUtil.getDrawable(mContext, R.drawable.rect_list_ripple_selected));
                    } else {
                        tv.setBackgroundColor(ResourcesUtil.getColor(mContext,
                                R.color.message_item_selected));
                    }
                } else {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                        tv.setBackground(ResourcesUtil.getDrawable(mContext, R.drawable.rect_list_ripple));
                    } else {
                        tv.setBackgroundColor(ResourcesUtil.getColor(mContext,
                                R.color.message_item_double));
                    }
                }
            }
            return tv;
        }
    };
}